<template>
  <div class="auto-listing-page">
    <!-- 页面标题头部 -->
    <div class="page-header">
      <div class="page-title">积分自动上架管理</div>
      <div class="page-subtitle">根据用户积分余额自动管理商品上架状态（1积分=1元）</div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-number">{{ stats.total_users || 0 }}</div>
              <div class="stats-label">总用户数</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-number">{{ stats.positive_balance_count || 0 }}</div>
              <div class="stats-label">积分充足用户</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-number">{{ stats.negative_balance_count || 0 }}</div>
              <div class="stats-label">积分不足用户</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-number">{{ stats.zero_balance_count || 0 }}</div>
              <div class="stats-label">零积分用户</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 操作区域 -->
    <el-card class="operation-card">
      <div class="operation-header">
        <h3>批量操作</h3>
        <div class="operation-buttons">
          <el-button type="primary" @click="batchAutoListing" :loading="batchLoading">
            <i class="el-icon-refresh"></i>
            一键自动上架所有用户
          </el-button>
          <el-button @click="loadStats" :loading="statsLoading">
            <i class="el-icon-refresh"></i>
            刷新统计
          </el-button>
        </div>
      </div>

      <!-- 积分规则配置 -->
      <div class="threshold-config">
        <h4>积分上架规则</h4>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="平均商品价格">
              <el-input-number
                v-model="pointsConfig.averagePrice"
                :min="100"
                :max="1000"
                :step="50"
                @change="updatePointsConfig"
              ></el-input-number>
              <span class="unit">积分</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="最大上架数量">
              <el-input-number
                v-model="pointsConfig.maxListing"
                :min="1"
                :max="50"
                :step="1"
                @change="updatePointsConfig"
              ></el-input-number>
              <span class="unit">个</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="操作说明">
              <el-tag type="info">根据积分余额智能上架商品，优先上架价格低的商品</el-tag>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 用户积分列表 -->
    <el-card class="table-card">
      <div class="table-header">
        <div class="table-title">用户积分列表</div>
        <div class="table-actions">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索用户昵称或ID"
            style="width: 200px; margin-right: 10px"
            clearable
            @input="handleSearch"
          >
            <i slot="prefix" class="el-icon-search"></i>
          </el-input>
          <el-button @click="loadUserBalances" :loading="loading">
            <i class="el-icon-refresh"></i>
            刷新
          </el-button>
        </div>
      </div>

      <el-table :data="userBalances" v-loading="loading" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="userId" label="用户ID" width="80"></el-table-column>
        <el-table-column prop="userNickname" label="用户昵称" width="150"></el-table-column>

        <el-table-column label="积分统计" width="200">
          <template slot-scope="scope">
            <div class="amount-info">
              <div class="amount-item">
                <span class="label">获得积分:</span>
                <span class="value positive">{{ scope.row.totalEarnedPoints || 0 }}</span>
              </div>
              <div class="amount-item">
                <span class="label">使用积分:</span>
                <span class="value negative">{{ scope.row.totalUsedPoints || 0 }}</span>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="积分余额" width="120">
          <template slot-scope="scope">
            <div class="balance-display">
              <el-tag :type="getPointsTagType(scope.row.pointsBalance)" size="medium">
                {{ scope.row.pointsBalance || 0 }}
              </el-tag>
              <div class="balance-status">
                {{ getPointsStatusText(scope.row.pointsBalance) }}
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="商品统计" width="150">
          <template slot-scope="scope">
            <div class="product-stats">
              <div class="product-item">
                <span class="label">总数:</span>
                <span class="value">{{ scope.row.productCount }}</span>
              </div>
              <div class="product-item">
                <span class="label">上架:</span>
                <span class="value online">{{ scope.row.onlineProductCount }}</span>
              </div>
              <div class="product-item">
                <span class="label">下架:</span>
                <span class="value offline">{{ scope.row.offlineProductCount }}</span>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="上架建议" width="200">
          <template slot-scope="scope">
            <div class="suggestion-display">
              <el-tag :type="getSuggestionTagType(scope.row.suggestedAction)" size="small">
                {{ getSuggestionText(scope.row.suggestedAction) }}
              </el-tag>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button
              @click="viewUserDetail(scope.row)"
              type="primary"
              size="mini"
              :loading="userDetailLoading"
              :disabled="userDetailLoading"
            >
              {{ userDetailLoading ? '加载中...' : '查看详情' }}
            </el-button>
            <el-button
              @click="autoListingUser(scope.row.userId)"
              :type="isPointsInsufficient(scope.row.pointsBalance) ? 'info' : 'success'"
              size="mini"
              :loading="scope.row.autoListingLoading"
              :disabled="scope.row.autoListingLoading || isPointsInsufficient(scope.row.pointsBalance)"
            >
              {{ getAutoListingButtonText(scope.row.pointsBalance) }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.count"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 批量操作结果对话框 -->
    <el-dialog title="批量操作结果" :visible.sync="batchResultVisible" width="800px">
      <div v-if="batchResults.length > 0">
        <el-table :data="batchResults" style="width: 100%">
          <el-table-column prop="userNickname" label="用户" width="120"></el-table-column>
          <el-table-column prop="action" label="操作" width="100">
            <template slot-scope="scope">
              <el-tag :type="getActionTagType(scope.row.action)" size="small">
                {{ getActionText(scope.row.action) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="actionDescription" label="描述" width="200"></el-table-column>
          <el-table-column prop="listedCount" label="上架数量" width="100"></el-table-column>
          <el-table-column prop="unlistedCount" label="下架数量" width="100"></el-table-column>
          <el-table-column prop="success" label="结果" width="80">
            <template slot-scope="scope">
              <el-tag :type="scope.row.success ? 'success' : 'danger'" size="small">
                {{ scope.row.success ? '成功' : '失败' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <!-- 用户详情对话框 -->
    <el-dialog title="用户详情" :visible.sync="userDetailVisible" width="900px">
      <div v-loading="userDetailLoading" :element-loading-text="userDetailLoading ? '正在加载用户详情...' : ''">
        <div v-if="currentUserDetail">
          <!-- 用户基本信息 -->
          <el-descriptions :column="2" border style="margin-bottom: 20px">
            <el-descriptions-item label="用户ID">{{ currentUserDetail.userId || '-' }}</el-descriptions-item>
            <el-descriptions-item label="用户昵称">{{ currentUserDetail.userNickname || '-' }}</el-descriptions-item>
            <el-descriptions-item label="获得积分">
              <span class="amount positive">{{ currentUserDetail.totalEarnedPoints || 0 }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="使用积分">
              <span class="amount negative">{{ currentUserDetail.totalUsedPoints || 0 }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="当前积分余额">
              <el-tag :type="getPointsTagType(currentUserDetail.pointsBalance)" size="medium">
                {{ currentUserDetail.pointsBalance || 0 }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="积分状态">
              {{ getPointsStatusText(currentUserDetail.pointsBalance) }}
            </el-descriptions-item>
            <el-descriptions-item label="商品总数">{{ currentUserDetail.productCount || 0 }}</el-descriptions-item>
            <el-descriptions-item label="上架商品数">{{
              currentUserDetail.onlineProductCount || 0
            }}</el-descriptions-item>
            <el-descriptions-item label="下架商品数">{{
              currentUserDetail.offlineProductCount || 0
            }}</el-descriptions-item>
            <el-descriptions-item label="上架建议">
              <el-tag :type="getSuggestionTagType(currentUserDetail.suggestedAction)" size="small">
                {{ getSuggestionText(currentUserDetail.suggestedAction) }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>

          <!-- 商品列表 -->
          <div v-if="userProducts && userProducts.length > 0">
            <h4>商品列表</h4>
            <el-table :data="userProducts" border style="margin-top: 10px">
              <el-table-column prop="spuId" label="SPU ID" width="80"></el-table-column>
              <el-table-column prop="spuTitle" label="商品标题" min-width="150"></el-table-column>
              <el-table-column prop="spuPrice" label="SPU价格" width="100">
                <template slot-scope="scope"> ¥{{ scope.row.spuPrice }} </template>
              </el-table-column>
              <el-table-column prop="skuCount" label="SKU数量" width="80"></el-table-column>
              <el-table-column prop="onlineSkuCount" label="上架SKU" width="80">
                <template slot-scope="scope">
                  <el-tag type="success" size="mini">{{ scope.row.onlineSkuCount }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="offlineSkuCount" label="下架SKU" width="80">
                <template slot-scope="scope">
                  <el-tag type="info" size="mini">{{ scope.row.offlineSkuCount }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="spuOnline" label="SPU状态" width="80">
                <template slot-scope="scope">
                  <el-tag :type="scope.row.spuOnline ? 'success' : 'info'" size="mini">
                    {{ scope.row.spuOnline ? '上架' : '下架' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120">
                <template slot-scope="scope">
                  <el-button type="text" size="mini" @click="viewProductSkus(scope.row)"> 查看SKU </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div v-else style="text-align: center; color: #999; padding: 20px">该用户暂无商品</div>
        </div>
      </div>
    </el-dialog>

    <!-- SKU详情对话框 -->
    <el-dialog title="SKU详情" :visible.sync="skuDetailVisible" width="800px">
      <div v-if="currentProductSkus && currentProductSkus.length > 0">
        <el-table :data="currentProductSkus" border>
          <el-table-column prop="skuId" label="SKU ID" width="80"></el-table-column>
          <el-table-column prop="skuTitle" label="SKU标题" min-width="150"></el-table-column>
          <el-table-column prop="skuPrice" label="价格" width="100">
            <template slot-scope="scope"> ¥{{ scope.row.skuPrice }} </template>
          </el-table-column>
          <el-table-column prop="skuDiscountPrice" label="折扣价" width="100">
            <template slot-scope="scope">
              <span v-if="scope.row.skuDiscountPrice">¥{{ scope.row.skuDiscountPrice }}</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column prop="skuCode" label="编码" width="120"></el-table-column>
          <el-table-column prop="skuStock" label="库存" width="80"></el-table-column>
          <el-table-column prop="skuOnline" label="状态" width="80">
            <template slot-scope="scope">
              <el-tag :type="scope.row.skuOnline ? 'success' : 'info'" size="mini">
                {{ scope.row.skuOnline ? '上架' : '下架' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="skuSpecs" label="规格" min-width="200">
            <template slot-scope="scope">
              <div v-if="scope.row.skuSpecs && scope.row.skuSpecs.length > 0">
                <el-tag v-for="spec in scope.row.skuSpecs" :key="spec.key_id" size="mini" style="margin-right: 5px">
                  {{ spec.key }}: {{ spec.value }}
                </el-tag>
              </div>
              <span v-else>-</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAutoListingStats,
  batchAutoListingAllUsers,
  getUserBalance,
  autoListingUserProducts,
  getUserBalanceList,
  getUserProducts } from '@/api/auto-listing'

export default {
  name: 'AutoListingManagement',
  data() {
    return {
      loading: false,
      statsLoading: false,
      batchLoading: false,
      userBalances: [],
      selectedRows: [],
      searchKeyword: '',
      stats: {},
      pointsConfig: {
        averagePrice: 500,
        maxListing: 20,
      },
      pagination: {
        page: 1,
        count: 20,
        total: 0,
      },
      batchResultVisible: false,
      batchResults: [],
      userDetailVisible: false,
      currentUserDetail: null,
      userProducts: [],
      skuDetailVisible: false,
      currentProductSkus: [],
      userDetailLoading: false,
    }
  },
  async mounted() {
    await this.loadStats()
    await this.loadUserBalances()
  },
  methods: {
    // 加载统计信息
    async loadStats() {
      try {
        this.statsLoading = true
        const response = await getAutoListingStats()
        this.stats = response
        this.pointsConfig.averagePrice = response.average_product_price || 500
        this.pointsConfig.maxListing = response.max_listing_count || 20
      } catch (error) {
        this.$message.error('加载统计信息失败')
        console.error('加载统计信息失败:', error)
      } finally {
        this.statsLoading = false
      }
    },

    // 加载用户余额列表
    async loadUserBalances() {
      try {
        this.loading = true
        const params = {
          page: this.pagination.page - 1, // 后端从0开始
          count: this.pagination.count,
          keyword: this.searchKeyword,
        }
        const response = await getUserBalanceList(params)
        this.userBalances = response.items || []
        this.pagination.total = response.total || 0

        // 为每个用户添加加载状态
        this.userBalances.forEach(user => {
          user.autoListingLoading = false
        })
      } catch (error) {
        this.$message.error('加载用户余额列表失败')
        console.error('加载用户余额列表失败:', error)
        // 如果API失败，使用模拟数据
        this.userBalances = await this.getMockUserBalances()
        this.pagination.total = this.userBalances.length
      } finally {
        this.loading = false
      }
    },

    // 模拟获取用户积分数据
    async getMockUserBalances() {
      // 这里应该调用真实API，暂时使用模拟数据
      const mockData = []
      for (let i = 1; i <= 20; i++) {
        const earnedPoints = Math.floor(Math.random() * 2000)
        const usedPoints = Math.floor(Math.random() * 1500)
        const pointsBalance = earnedPoints - usedPoints

        let suggestedAction = '积分不足，无法上架商品'
        if (pointsBalance >= 1000) {
          suggestedAction = `积分充足，可上架${ Math.floor(pointsBalance / 500) }个商品`
        } else if (pointsBalance >= 500) {
          suggestedAction = `积分良好，可上架${ Math.floor(pointsBalance / 500) }个商品`
        } else if (pointsBalance >= 100) {
          suggestedAction = '积分一般，可上架1个商品'
        } else if (pointsBalance > 0) {
          suggestedAction = '积分较少，可上架1个商品'
        }

        mockData.push({
          userId: i,
          userNickname: `用户${i}`,
          totalEarnedPoints: earnedPoints,
          totalUsedPoints: usedPoints,
          pointsBalance,
          suggestedAction,
          productCount: Math.floor(Math.random() * 10) + 1,
          onlineProductCount: Math.floor(Math.random() * 5),
          offlineProductCount: Math.floor(Math.random() * 5),
          autoListingLoading: false,
        })
      }
      return mockData
    },

    // 批量自动上架
    async batchAutoListing() {
      try {
        this.batchLoading = true
        const response = await batchAutoListingAllUsers()

        // 检查响应状态
        if (response.code === 0) {
          this.$message.success(response.message || '批量自动上架完成')
          await this.loadStats()
          await this.loadUserBalances()
        } else {
          this.$message.error(response.message || '批量自动上架失败')
        }
      } catch (error) {
        this.$message.error(`批量自动上架失败: ${ error.message || '未知错误'}`)
        console.error('批量自动上架失败:', error)
      } finally {
        this.batchLoading = false
      }
    },

    // 单个用户自动上架
    async autoListingUser(userId) {
      try {
        // 设置加载状态
        const user = this.userBalances.find(u => u.userId === userId)
        if (user) {
          user.autoListingLoading = true
        }

        const response = await autoListingUserProducts(userId)

        // 检查响应状态
        if (response.code === 0) {
          this.$message.success(response.message || `用户 ${userId} 自动上架完成`)
          await this.loadStats()
          await this.loadUserBalances()
        } else {
          this.$message.error(response.message || `用户 ${userId} 自动上架失败`)
        }
      } catch (error) {
        this.$message.error(`用户 ${userId} 自动上架失败: ${error.message || '未知错误'}`)
        console.error('自动上架失败:', error)
      } finally {
        // 清除加载状态
        const user = this.userBalances.find(u => u.userId === userId)
        if (user) {
          user.autoListingLoading = false
        }
      }
    },

    // 查看用户详情
    async viewUserDetail(user) {
      try {
        this.userDetailLoading = true
        // 初始化数据
        this.currentUserDetail = null
        this.userProducts = []

        // 获取用户基本信息
        const response = await getUserBalance(user.userId)
        if (response && !response.error) {
          this.currentUserDetail = response
        } else {
          const errorMsg = response && response.error ? response.error : '获取用户基本信息失败'
          this.$message.error(errorMsg)
          return
        }

        // 获取用户商品列表
        const productsResponse = await getUserProducts(user.userId)
        console.log('商品列表API响应:', productsResponse)

        if (productsResponse && Array.isArray(productsResponse)) {
          // 直接使用返回的数组
          this.userProducts = productsResponse
          console.log('设置的商品列表:', this.userProducts)
        } else {
          this.userProducts = []
          console.warn('获取用户商品列表失败: 返回数据不是数组格式')
        }

        this.userDetailVisible = true
      } catch (error) {
        this.$message.error('获取用户详情失败')
        console.error('获取用户详情失败:', error)
        this.currentUserDetail = null
        this.userProducts = []
      } finally {
        this.userDetailLoading = false
      }
    },

    // 查看商品SKU详情
    viewProductSkus(product) {
      this.currentProductSkus = product.skus || []
      this.skuDetailVisible = true
    },

    // 更新积分配置
    updatePointsConfig() {
      // 这里应该调用API更新积分配置
      this.$message.info('积分配置已更新')
    },

    // 搜索处理
    handleSearch() {
      // 实现搜索逻辑
      this.loadUserBalances()
    },

    // 选择处理
    handleSelectionChange(selection) {
      this.selectedRows = selection
    },

    // 分页处理
    handleSizeChange(val) {
      this.pagination.count = val
      this.pagination.page = 1
      this.loadUserBalances()
    },

    handleCurrentChange(val) {
      this.pagination.page = val
      this.loadUserBalances()
    },

    // 格式化金额
    formatAmount(amount) {
      if (!amount) return '0.00'
      return parseFloat(amount).toFixed(2)
    },

    // 获取积分标签类型
    getPointsTagType(points) {
      if (points >= 1000) return 'success'
      if (points >= 100) return 'warning'
      if (points > 0) return 'info'
      return 'danger'
    },

    // 获取积分状态文本
    getPointsStatusText(points) {
      if (points >= 1000) return '积分充足'
      if (points >= 100) return '积分一般'
      if (points > 0) return '积分较少'
      return '积分不足'
    },

    // 判断积分是否不足（无法上架商品）
    isPointsInsufficient(points) {
      return !points || points <= 0
    },

    // 获取自动上架按钮文本
    getAutoListingButtonText(points) {
      if (!points || points <= 0) {
        return '积分不足'
      }
      return '自动上架'
    },

    // 获取建议标签类型
    getSuggestionTagType(action) {
      if (action && action.includes('充足')) return 'success'
      if (action && action.includes('良好')) return 'warning'
      if (action && action.includes('一般')) return 'info'
      if (action && action.includes('较少')) return 'warning'
      if (action && action.includes('不足')) return 'danger'
      return 'info'
    },

    // 获取建议文本
    getSuggestionText(action) {
      if (!action) return '未知'
      // 截取前20个字符，避免显示过长
      return action.length > 20 ? `${action.substring(0, 20) }...` : action
    },
  },
}
</script>

<style lang="scss" scoped>
.auto-listing-page {
  padding: 16px 16px 24px;
}

.page-header {
  margin-bottom: 16px;
  .page-title {
    font-size: 18px;
    font-weight: 600;
    line-height: 1.2;
  }
  .page-subtitle {
    margin-top: 4px;
    color: #909399;
    font-size: 12px;
  }
}

.stats-cards {
  margin-bottom: 20px;
  margin-top: 4px;

  .stats-card {
    .stats-content {
      text-align: center;

      .stats-number {
        font-size: 24px;
        font-weight: bold;
        color: #409eff;
        margin-bottom: 8px;
      }

      .stats-label {
        font-size: 14px;
        color: #666;
      }
    }
  }
}

.operation-card {
  margin-bottom: 20px;

  .operation-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h3 {
      margin: 0;
      color: #333;
    }

    .operation-buttons {
      .el-button {
        margin-left: 10px;
      }
    }
  }

  .threshold-config {
    h4 {
      margin-bottom: 15px;
      color: #333;
    }

    .unit {
      margin-left: 5px;
      color: #666;
    }
  }
}

.table-card {
  .table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .table-title {
      font-size: 16px;
      font-weight: bold;
    }

    .table-actions {
      display: flex;
      align-items: center;
    }
  }
}

.amount-info {
  .amount-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 4px;

    .label {
      color: #666;
      font-size: 12px;
    }

    .value {
      font-weight: 500;

      &.positive {
        color: #67c23a;
      }

      &.negative {
        color: #f56c6c;
      }
    }
  }
}

.balance-display {
  text-align: center;

  .balance-status {
    margin-top: 4px;
    font-size: 12px;
    color: #666;
  }
}

.product-stats {
  .product-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 2px;

    .label {
      color: #666;
      font-size: 12px;
    }

    .value {
      font-weight: 500;

      &.online {
        color: #67c23a;
      }

      &.offline {
        color: #909399;
      }
    }
  }
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}

.amount {
  font-weight: 500;

  &.positive {
    color: #67c23a;
  }

  &.negative {
    color: #f56c6c;
  }
}

.suggestion-display {
  .el-tag {
    max-width: 100%;
    white-space: normal;
    word-break: break-all;
    line-height: 1.2;
  }
}
</style>
